package com.cloudpush.web.servlet;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.xwork.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.multitype.GenericManageableCaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * @author wulibin, exceptsky@gmail.com, 2012-3-9 下午1:37:04
 * 
 */
public class ImageCaptchaServlet extends HttpServlet {
		private static final long serialVersionUID = 1L;
		private GenericManageableCaptchaService captchaService;

		@Override  
	    public void init() throws ServletException {          
	        super.init();  
	        ServletContext servletContext = this.getServletContext();  
	        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);  
	        captchaService = (GenericManageableCaptchaService)ctx.getBean("captchaService");  
	    } 
		
	    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {

	       byte[] captchaChallengeAsJpeg = null;
	       // the output stream to render the captcha image as jpeg into
	        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
	        try {
	        // get the session id that will identify the generated captcha.
	        //the same id must be used to validate the response, the session id is a good candidate!
	        String token = httpServletRequest.getParameter("token");
	        if(StringUtils.isEmpty(token)){
	        	token="123";
	        }
	        // call the ImageCaptchaService getChallenge method
	            BufferedImage challenge =  captchaService.getImageChallengeForID(token,
	                            httpServletRequest.getLocale());
	            // a jpeg encoder
	            JPEGImageEncoder jpegEncoder =
	                    JPEGCodec.createJPEGEncoder(jpegOutputStream);
	            jpegEncoder.encode(challenge);
	        } catch (IllegalArgumentException e) {
	            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
	            return;
	        } catch (CaptchaServiceException e) {
	            httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
	            return;
	        }

	        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

	        // flush it in the response
	        httpServletResponse.setHeader("Cache-Control", "no-store");
	        httpServletResponse.setHeader("Pragma", "no-cache");
	        httpServletResponse.setDateHeader("Expires", 0);
	        httpServletResponse.setContentType("image/jpeg");
	        ServletOutputStream responseOutputStream =
	                httpServletResponse.getOutputStream();
	        responseOutputStream.write(captchaChallengeAsJpeg);
	        responseOutputStream.flush();
	        responseOutputStream.close();
	    }

		public void setCaptchaService(GenericManageableCaptchaService captchaService) {
			this.captchaService = captchaService;
		}
	    
}
